﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.DataAccess.Entities;
using CRM.Business.Services;
using CRM.Encryption;
using Telerik.Web.UI;

namespace Web.Account
{
    public partial class Users : System.Web.UI.Page
    {
        static List<USER_DETAIL> UserDetails = new List<USER_DETAIL>();
        static USER user;
        static bool check;
        static ROLE r;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;
             user = (USER)Session["User"];
             List<USER_DETAIL> uds;
             if (user != null)
             {
                 r = RoleService.GetRoleByID((long)user.ROLE_ID);
                 if (((bool)user.IS_ADMIN) || ((bool)r.IS_MANAGER))
                 {
                     check = false;
                     uds = bindGrid("", null, "", "", null);
                     LoadRole();
                     LoadEmailTemplate();
                     UserDetails = LoadListUser(uds);
                     RadGrid1.DataSource = UserDetails;
                     RadGrid1.DataBind();
                 }
                 else
                 {
                     Response.Redirect("../Home.aspx");
                 }
             }
             else
             {
                 RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessageAndRedirect('" + "Please login before continue !" + "','" + "Login.aspx" + "');");
             }
        }
        public List<USER_DETAIL> LoadListUser(List<USER_DETAIL> uds)
        {
            List<USER_DETAIL> Lresult = new List<USER_DETAIL>();
            
            if ((bool)user.IS_SUPER_USER)
            {
                for (int i = 0; i < uds.Count; i++)
                {
                    if (user.ID != uds[i].UserID)
                        Lresult.Add(uds[i]);
                }

            }
            else
            {
                for (int i = 0; i < uds.Count; i++)
                {
                    if ((user.ID != uds[i].UserID) && (uds[i].IS_SUPER_USER == false) && (uds[i].IS_ADMIN == false))
                        Lresult.Add(uds[i]);
                }
            }
            return Lresult;

        }
        private void LoadEmailTemplate()
        {
            ddlEmailTemplate.DataSource = EmailTemplateService.GetEmailTemplateByCondition("", "", "");
            ddlEmailTemplate.DataBind();
            ddlEmailTemplate.Items.Insert(0, new RadComboBoxItem("None", "-1"));
        }
        private void LoadRole()
        {
            ddlRole.DataSource = RoleService.GetRoles();
            ddlRole.DataBind();
            ddlRole.Items.Insert(0, new RadComboBoxItem("Select an option", "-1"));
        }

        private List<USER_DETAIL> bindGrid(string UserName, bool? isAdmin, string primaryemail, string officephone, long? RoleID)
        {
            List<USER_DETAIL> us = UserService.GetUserByCondition(UserName, isAdmin, primaryemail, officephone, RoleID);
            if (us == null)
            {
                us = new List<USER_DETAIL>();
            }
            return us;
        }
        protected void RadGrid1_PreRender(object sender, EventArgs e)
        {

            if (!(bool)user.IS_SUPER_USER)
            {
                RadGrid1.MasterTableView.GetColumn("IS_ADMIN").Visible = false;

            }
        }
        protected void RadGrid1_ItemCommand(object source, GridCommandEventArgs e)
        {
            GridDataItem dataItem = e.Item as GridDataItem;
            switch (e.CommandName)
            {
                case "Edit":
                    Response.Redirect("EditUser.aspx?id=" + dataItem["UserID"].Text);
                    break;
                case "Delete":
                    long userID = Convert.ToInt64(dataItem["UserID"].Text);
                    System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)dataItem["GridImageColumn"].Controls[0];
                    string sImg = img.ImageUrl;
                    int deleteuser = UserService.DeleteUser(userID);
                    if (deleteuser == 1)
                    {
                        UserDetails.Remove(UserDetails.Where(x => x.UserID == userID).FirstOrDefault<USER_DETAIL>());
                        System.IO.File.Delete(Server.MapPath(sImg));
                        RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Delete user successful !" + "');");
                        //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Delete user successful !');", true);
                    }
                    else
                        RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Can not delete this user !" + "');");
                        //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Cannot delete user !');", true);
                    break;
                default:
                    break;
            }
        }
        protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            RadGrid1.DataSource = UserDetails;
        }

        protected void btnSearch_ServerClick(object sender, EventArgs e)
        {
            bool? isAdmin = false;
            if (RadButton1.Checked == true)
                isAdmin = true;
            if (RadButton2.Checked == true)
                isAdmin = false;
            if (RadButton3.Checked == true)
                isAdmin = null;
            long? at = null;
            if (ddlRole.SelectedValue != "-1")
                at = Convert.ToInt64(ddlRole.SelectedValue);

            List<USER_DETAIL> uds = bindGrid(txtUserName.Text.Trim(), isAdmin, txtEmail.Text.Trim(), txtPhone.Text.Trim(), at);
            UserDetails = LoadListUser(uds);
            
            RadGrid1.DataSource = UserDetails;
            RadGrid1.DataBind();
        }

        protected void btnAddUser_ServerClick(object sender, EventArgs e)
        {
            Response.Redirect("Register.aspx");
        }

        protected void sendEmail_Click(object sender, EventArgs e)
        {
            LinkButton lbtnSendEmail = sender as LinkButton;
            EMAIL_TEMPLATE email = new EMAIL_TEMPLATE();
            email.SUBJECT = " ";
            email.MESSAGE = " ";
            EMAIL_TEMPLATE emailTemplate = EmailTemplateService.GetEmailTemplateByID(Convert.ToInt64(ddlEmailTemplate.SelectedValue.ToString()));
            if (emailTemplate != null)
            {
                email = emailTemplate;

            }
            string mailto = lbtnSendEmail.Text;
            string t = "parent.location='mailto:" + mailto + "?Subject=" + email.SUBJECT + "&Body=" + email.MESSAGE.Replace(" ", "%20").Replace("\r\n", "%0A") + "'";
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", t, true);
        }

        protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridPagerItem)
            {
                GridPagerItem oGridPagerItem = (GridPagerItem)e.Item;
                RadComboBox oRadComboBox = (RadComboBox)oGridPagerItem.FindControl("PageSizeComboBox");
                oRadComboBox.Width = Unit.Pixel(50);
            }
        }
        
        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem && check == false )
            {
                check = false;
                GridDataItem item = e.Item as GridDataItem;
                RadComboBox ddlRoleName = (RadComboBox)item.FindControl("ddlRoleName");
                ddlRoleName.DataSource = RoleService.GetRoles();
                ddlRoleName.DataBind();
                ddlRoleName.Items.Insert(0, new RadComboBoxItem("Select an option", "-1"));

                RadComboBoxItem ritem = ddlRoleName.FindItemByValue(item.GetDataKeyValue("ROLE_ID").ToString());

                if (ritem != null)
                {
                    ddlRoleName.ClearSelection();
                    ritem.Selected = true;
                }
            }
           
        }

        protected void ddlRoleName_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {
            RadComboBox ddlRoleName = (sender as RadComboBox);
            GridDataItem item = ddlRoleName.Parent.Parent as GridDataItem;
            USER user = new USER();
            long UserID = (long)item.GetDataKeyValue("UserID");
            user = UserService.GetUserByID(UserID);
            user.ROLE_ID = Convert.ToInt64(e.Value);

            int updateUser = UserService.UpdateUser(user);
            if (updateUser != 1)
            {
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Can not update role for this user !" + "');");
                //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Can not update role for this user !');", true);
            }
        }
        protected void chbActive_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chk = (CheckBox)sender;
            bool status = chk.Checked;
            GridDataItem item = (GridDataItem)chk.NamingContainer;
            long userID = (long)item.GetDataKeyValue("UserID");

            USER user = new USER();
            user = UserService.GetUserByID(userID);
            user.ACTIVE = status;

            //update thong qua USER_DETAIL
            int updateUser = UserService.UpdateUser(user);
            if (updateUser != 1)
            {
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Can not update status for this user !" + "');");
                //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Can not update status for this user !');", true);
            }
        }
        protected void chbIsAdmin_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox chk = (CheckBox)sender;
            bool status = chk.Checked;
            GridDataItem item = (GridDataItem)chk.NamingContainer;
            long userID = (long)item.GetDataKeyValue("UserID");

            USER user = new USER();
            user = UserService.GetUserByID(userID);
            user.IS_ADMIN = status;
            int updateUser = UserService.UpdateUser(user);
            if (updateUser != 1)
            {
                chk.Checked = chk.Checked ? false : true;
                RadAjaxManager.GetCurrent(this).ResponseScripts.Add(@"ShowMessage('" + "Can not update access right for this user !" + "');");
                //ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "", "alert('Can not update access right for this user !');", true);
            }
        }
        protected void lbtnExportToCSV_ServerClick(object sender, EventArgs e)
        {
            check = true;
            RadGrid1.ExportSettings.IgnorePaging = true;
            RadGrid1.ExportSettings.OpenInNewWindow = true;
            RadGrid1.ExportSettings.UseItemStyles = true;
            DateTime dt = DateTime.Now;
            RadGrid1.ExportSettings.FileName = "Users_" + dt.Year + dt.Month + dt.Day;
            RadGrid1.MasterTableView.GetColumn("TOOLS").Display = false;
            RadGrid1.MasterTableView.GetColumn("GridImageColumn").Display = false;
            RadGrid1.MasterTableView.GetColumn("ROLE_NAME").Visible = false;
            RadGrid1.MasterTableView.GetColumn("ROLE_NAME_TO_EXPORT").Display = true;
            RadGrid1.MasterTableView.ExportToCSV();
        }
    }
}